<template>
  <div class="rule-setting-container">
    <h2 class="rule-section-title">
      <el-popover
        placement="bottom-start"
        width="500"
        trigger="hover"
        :content="$t('performance.placeholder.ruleSetting')">
        <span style="vertical-align: middle" slot="reference">
          {{$t('performance.title.performanceRule')}}<i class="icon-help iconfont" style="margin-left: 3px;"></i>
        </span>
      </el-popover>

      <!-- <base-button type="primary" native-type="submit" @event="openSettingDialog">{{$t('common.base.add2')}}</base-button> -->
      <el-button type="primary" icon="el-icon-plus" @click="openSettingDialog">{{$t('common.base.create')}}</el-button>
    </h2>

    <el-table
      border
      :data="rules"
      v-loading="loading"
      class="rule-table"
      :highlight-current-row="false"
      header-row-class-name="common-list-table-header__v2">
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        show-overflow-tooltip
      >

        <template slot-scope="scope">
          <template v-if="column.field === 'ruleType'">
            {{scope.row[column.field] | ruleType}}
          </template>
          <template v-else-if="column.field === 'effect'">
            <el-switch
              :disabled="scope.row.pending"
              @change="toggleStatus(scope.row)"
              :value="Boolean(scope.row.effect)">
            </el-switch>
            <span style='margin-left:2px;font-size:12px;'>{{ scope.row.effect == '1' ? '启用' : '禁用' }}</span>
          </template>
          <template v-else-if="column.field === 'action'">
            <el-button type="text" @click="editRule(scope.row)">{{$t('common.base.edit')}}</el-button>
            <el-button type="text" @click="deleteRule(scope.row)">{{$t('common.base.delete')}}</el-button>
          </template>

          <template v-else>
            {{scope.row[column.field]}}
          </template>
        </template>

      </el-table-column>
    </el-table>

    <setting-rule-dialog @refresh-rules="fetchRules" :all-types="allTypes" :performance-rule="editedPerformanceRule" ref="settingRuleDialog" />
  </div>
</template>

<script>
import SettingRuleDialog from './components/SettingRuleDialog.vue';
import {getAllPerformanceRules, deletePerformanceRule, togglePerformanceRuleEffect} from '@src/api/PerformanceApi';
import { t } from '@src/locales';

export default {
  name: 'rule-setting',
  props: {
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      rules: [],
      columns: this.buildColumns(),
      loading: false,
      editedPerformanceRule: {},
    }
  },
  computed: {
    allTypes() {
      const { serviceType, serviceContent, templateId} = this.initData;
      return {
        taskTypes: (templateId || []).map(({templateName, templateId}) => ({
          label: templateName,
          value: templateId,
        })),
        serviceTypes: (serviceType || []).map(st => ({
          label: st,
          value: st,
        })),
        serviceContents: (serviceContent || []).map(sc => ({
          label: sc,
          value: sc,
        })),
      };
    }
  },
  filters: {
    ruleType(val) {
      return val ? t('performance.label.prizeRule') : t('performance.label.scoreRule');
    }
  },
  mounted() {
    this.fetchRules();

  },
  methods: {
    editRule(row) {
      this.$refs.settingRuleDialog.toggleDialog({
        ...row,
        ruleContent: JSON.parse(row.ruleContent)
      })
    },
    openSettingDialog() {
      this.$refs.settingRuleDialog.toggleDialog();
    },
    fetchRules() {
      this.loading = true;
      getAllPerformanceRules()
        .then(res => {
          this.loading = false;

          if (res.status) return this.$platform.notification({
            title: t('common.base.fail'),
            type: 'error',
            message: res.message || t('common.base.tip.unknownError2'),
          });

          this.rules = (res.data || [])
            .map(rule => ({
              ...rule,
              pending: false,
            }))

        })
        .catch(e => console.error('e', e));
    },
    toggleStatus(row) {
      const ns = row.effect ? 0 : 1;
      row.pending = true;
      const params = {
        id: row.id,
        effect: ns,
      };

      togglePerformanceRuleEffect(params)
        .then(res => {
          row.pending = false;
          if (res.status) {
            return this.$platform.notification({
              title: t('common.base.fail'),
              type: 'error',
              message: res.message || t('common.base.tip.unknownError2'),
            })
          }

          this.rules.forEach(rule => {
            if (rule.id === row.id) {
              rule.effect = ns;
            }
          })
        })
        .catch(e => console.error('e', e));
    },
    async deleteRule(row) {
      const result = await this.$platform.confirm(t('performance.tip.deleteRuleConfirm'));
      if (!result) return;

      deletePerformanceRule(row.id)
        .then(res => {
          if (res.status) return this.$platform.notification({
            title: t('common.base.fail'),
            type: 'error',
            message: res.message || t('common.base.tip.unknownError2'),
          });

          this.$platform.notification({
            title: t('common.base.tip.deleteSuccess'),
            type: 'success',
          });

          // 删除成功
          this.fetchRules();
        })
        .catch(e => console.error('e', e));
    },
    notice({type, message, title}) {
      return this.$platform.notification({
        title,
        message: (h => (<div>{message}</div>))(this.$createElement),
        type,
      });
    },
    buildColumns() {
      return [
        {
          label: t('common.base.rulerName'),
          field: 'ruleName',
          show: true,
          width: '200px'
        },
        {
          label: t('common.base.rulerTip'),
          field: 'ruleDesc',
          show: true,
          // width: '300px'
        },
        {
          label: t('common.fields.catalog.displayName'),
          field: 'ruleType',
          show: true,
          width: '80px'
        },
        {
          label: t('common.label.enableOrDisabled'),
          field: 'effect',
          show: true,
          width: '90px'
        },
        {
          label: t('common.base.operation'),
          field: 'action',
          show: true,
          width: '160px'
        },
      ]
    }
  },
  components: {
    [SettingRuleDialog.name]: SettingRuleDialog,
  }
}
</script>

<style lang="scss">

  .rule-setting-container {
    background: #ffffff;
    padding: 10px;

    .rule-section-title {
      display: flex;
      justify-content: space-between;
      line-height: 32px;
      font-size: 16px;
      margin: 0;
    }

    // table
    .rule-table {
      margin-top: 10px;
      th {
        background: #F5F5F5;
        color: $text-color-primary;
        font-weight: normal;
        font-size: 14px;
        line-height: 34px;
        color: #333;
      }
      td {
        font-size: 13px;
      }
    }
  }

</style>
